package com.cee.admin.modules.prod.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cee.admin.common.BaseController;
import com.cee.common.annotations.OrderParam;
import com.cee.common.exception.GlobalException;
import com.cee.common.spring.SpringContextHolder;
import com.cee.common.web.result.Result;
import com.cee.common.web.result.ResultCode;
import com.cee.domain.constants.DomainConstants;
import com.cee.domain.modules.prod.dto.ProdProductGeneralFillFormDTO;
import com.cee.domain.modules.prod.entity.ProdProductDataReport;
import com.cee.domain.modules.prod.vo.ProdProductDataReportVo;
import com.cee.domain.modules.sys.entity.SysFrontUser;
import com.cee.ds.common.utils.BasePrincipalUtils;
import com.cee.ds.modules.cc.mapper.CcEmissionSourceMapper;
import com.cee.ds.modules.prod.general.service.IProdGeneralService;
import com.cee.ds.modules.prod.service.IProdProductDataReportService;
import com.cee.ds.modules.sys.service.ISysFrontUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 铝产品表 前端控制器
 * </p>
 *
 * @author autoGenerator
 * @since 2024-03-07
 */
@Tag(name = "产品管理-产品数据填报")
@RestController
@RequestMapping("/api/prod/data/report")
public class ProdProductDataReportController extends BaseController {

    @Autowired
    private IProdProductDataReportService prodProductDataReportService;

    @Autowired
    private CcEmissionSourceMapper ccEmissionSourceMapper;

    @Autowired
    private IProdGeneralService generalService;


    @Operation(summary = "分页查询产品数据填报")
    @GetMapping("/page")
    public Result<Page<ProdProductDataReportVo>> page(@RequestParam Long current, @RequestParam Long size, @OrderParam ProdProductDataReportVo dataReport){
        handleOrder(dataReport);
        dataReport.setCityId(BasePrincipalUtils.currentUser().getCityId());
        return success(prodProductDataReportService.queryPageVo(new Page<>(current,size),dataReport));
    }

    @PostMapping("/examine")
    @Operation(summary = "审核产品数据填报")
    @RequiresPermissions("prod:data:report:examine")
    public Result<Boolean> examine(@RequestParam Long id, @RequestParam String examineStatus, String examineNote){
        ProdProductDataReport old = prodProductDataReportService.getById(id);
        if(!DomainConstants.COMMON_UNAUDITED_STATUS.equals(old.getExamineStatus())){
            throw new GlobalException("状态为未审核的填报才能进行审核");
        }
        Integer cityId = BasePrincipalUtils.currentUser().getCityId();
        if (cityId != null) {
            SysFrontUser frontUser = SpringContextHolder.getBean(ISysFrontUserService.class).getById(old.getBelongUser());
            if (frontUser != null && !Objects.equals(cityId, frontUser.getCityId())) {
                throw new GlobalException(ResultCode.NOT_PERMISSION);
            }
        }
        ProdProductDataReport dataReport = new ProdProductDataReport();
        dataReport.setId(id);
        dataReport.setExamineStatus(examineStatus);
        dataReport.setExamineNote(examineNote);
        dataReport.setExamineTime(new Date());
        dataReport.setExamineUserId(BasePrincipalUtils.currentUserId());
        return success(prodProductDataReportService.updateById(dataReport));
    }

    @PostMapping("/examine/general")
    @Operation(summary = "审核通用产品数据填报")
    @RequiresPermissions("prod:data:report:examine")// 填报数据id。排放因子
    public Result<Boolean> examineGeneral(@RequestBody ProdProductGeneralFillFormDTO formDto){
        Long id = formDto.getProdProductGeneralFillForm().getBaseInfo().getDataReportId();
        ProdProductDataReport old = prodProductDataReportService.getById(id);
        if(!DomainConstants.COMMON_UNAUDITED_STATUS.equals(old.getExamineStatus())){
            throw new GlobalException("状态为未审核的填报才能进行审核");
        }
        generalService.upsert(formDto.getProdProductGeneralFillForm(), formDto.getExamineStatus());// 审核之前进行一次具备排放因子的计算
        Integer cityId = BasePrincipalUtils.currentUser().getCityId();
        if (cityId != null) {
            SysFrontUser frontUser = SpringContextHolder.getBean(ISysFrontUserService.class).getById(old.getBelongUser());
            if (frontUser != null && !Objects.equals(cityId, frontUser.getCityId())) {
                throw new GlobalException(ResultCode.NOT_PERMISSION);
            }
        }
        ProdProductDataReport dataReport = new ProdProductDataReport();
        dataReport.setId(id);
        dataReport.setExamineStatus(formDto.getExamineStatus());
        dataReport.setExamineNote(formDto.getExamineNote());
        dataReport.setExamineTime(new Date());
        dataReport.setExamineUserId(BasePrincipalUtils.currentUserId());
        return success(prodProductDataReportService.updateById(dataReport));
    }

    @Operation(summary = "查询供应厂商数据填报的年份")
    @GetMapping("/supplier/reportYear/list")
    public Result<List<Integer>> listSupplierReportYear(@RequestParam Long productId){
        return success(prodProductDataReportService.queryChainWrapper().select("report_year").eq("product_id",productId).eq("examine_status","2").list().stream().map(ProdProductDataReport::getReportYear).collect(Collectors.toList()));
    }

    @Operation(summary = "查询供应厂商数据填报的季度")
    @GetMapping("/supplier/reportQuarter/list")
    public Result<List<ProdProductDataReport>> listSupplierReportQuarter(@RequestParam Long productId, @RequestParam Long reportYear){
        return success(prodProductDataReportService.queryChainWrapper().select("id","report_quarter","unit_product_emissions").eq("product_id",productId).eq("report_year",reportYear).eq("examine_status","2").list());
    }

    @Operation(summary = "查询燃料类型列表")
    @GetMapping("/fuel/type/list")
    public Result<List<Map<String,Object>>> listFuelType(){
        return success(ccEmissionSourceMapper.listAll().stream().map(item->{
            Map<String, Object> map = new HashMap<>(2);
            map.put("code",item.getId());
            map.put("name",item.getName());
            return map;
        }).collect(Collectors.toList()));
    }
}
